
const moment = require('moment');
const request = require("request");
const now = () => {
    return moment().format('YYYY-MM-DD HH:mm:ss')
};
//全局配置文件
const config = require("../config/config");
const logger = require("../common/logger");
const co = require("co")

//数据库模型
const access_token = require("../model/index").access_token;
const signintable = require("../model/index").signintable;
const Singrecord = require("../model/index").singrecord;
module.exports = {
    //随机数
    mathRandom: function (arr) {
        let Range = arr[0] - arr[1],
            Rand = Math.random(),
            num = arr[1] + Math.ceil(Rand * Range); //四舍五入
        return num;
    },
    //获取小程序access_token
    access_token() {
        try {
            request({
                url: config.appSecreturl + "grant_type=client_credential&appid=" + config.appID + "&secret=" + config.appSecret,
                method: "post",
                json: true,
                headers: {
                    "content-type": "application/json",
                },
            }, function (error, response, body) {
                if (response.statusCode == 200) {
                    logger.info("小程序请求access_token成功.")
                    access_token.find().then((data) => {//查询数据表是否存在
                        if (!data) {//数据不存在添加数据
                            return access_token.create({ access_token: body.access_token, appID: config.appID, time: now() })
                        } else {//数据存在更新数据
                            return access_token.update({ access_token: body.access_token, time: now() }, {
                                where: { appID: config.appID },
                            })
                        }
                    }).catch(err => {
                        logger.error("小程序更新access_token失败" + err, body)
                    })
                } else {
                    logger.info("小程序请求access_token失败", body)
                }
            })
        } catch (error) {
            logger.error(error)
        }
    },
    //更新用户运动数据
    updateWeRunData(openId, data) {
        return new Promise((resolve, rejiect) => {
            co(function* () {
                for (let i = 0; i < data.length; i++) {
                    let datas = yield signintable.findOne({ where: { openid: openId, signdate: data[i].timestamp } });
                    let signdate = yield signintable.findOne({ where: { openid: openId }, order: [['signdate', 'DESC']] });
                    let ids;

                    if (!datas) {
                        if (!signdate) {
                            ids = yield signintable.create({
                                openid: openId, steps: data[i].step, signdate: data[i].timestamp,
                                weight: 0.00, bust: 0.00, waist: 0.00, hipline: 0.00,
                                arm: 0.00, thigh: 0.00, calf: 0.00,
                                recordtime: data[i].timestamp, signin_weight: 0, signin_bust: 0, signin_waist: 0,
                                signin_hipline: 0, signin_arm: 0, signin_thigh: 0, signin_calf: 0
                            })
                        } else {
                            if (moment(signdate.signdate).format('YYYY-MM-DD') > moment(data[i].timestamp).format('YYYY-MM-DD')) {
                                ids = yield signintable.create({
                                    openid: openId, steps: data[i].step, signdate: data[i].timestamp,
                                    weight: 0.00, bust: 0.00, waist: 0.00, hipline: 0.00,
                                    arm: 0.00, thigh: 0.00, calf: 0.00,
                                    recordtime: data[i].timestamp, signin_weight: 0, signin_bust: 0, signin_waist: 0,
                                    signin_hipline: 0, signin_arm: 0, signin_thigh: 0, signin_calf: 0
                                })
                            } else {
                                ids = yield signintable.create({
                                    openid: openId, steps: data[i].step, signdate: data[i].timestamp,
                                    weight: signdate == null ? 0.00 : signdate.weight, bust: signdate == null ? 0.00 : signdate.bust, waist: signdate == null ? 0.00 : signdate.waist, hipline: signdate == null ? 0.00 : signdate.hipline,
                                    arm: signdate == null ? 0.00 : signdate.arm, thigh: signdate == null ? 0.00 : signdate.thigh, calf: signdate == null ? 0.00 : signdate.calf,
                                    recordtime: data[i].timestamp, signin_weight: 0, signin_bust: 0, signin_waist: 0,
                                    signin_hipline: 0, signin_arm: 0, signin_thigh: 0, signin_calf: 0
                                })
                            }
                        }

                    } else {
                        //更新最后一条数据
                        if (i == (data.length) - 1 || i == (data.length) - 2) {
                            ids = yield datas.update({
                                steps: data[i].step
                            }, { where: { openid: openId, signdate: data[i].timestamp } })
                        }
                    }
                }
                resolve(true)
            }).catch(err => {
                rejiect(err)
                logger.error(err)
            })
        })
    },
    //签到详情
    Singrecord(openid, recordtime, obj) {
        Singrecord.create(obj).then(() => {
            logger.info("保存成功")
        }).catch(err => {
            logger.error(err)
        })
    },
    //发送请求
    requestPOST(url, body) {
        return new Promise((resolve, reject) => {
            request({
                url: url,
                method: "POST",
                json: true,
                headers: {
                    "content-type": "application/json",
                },
                body: body
            }, function (error, response, body) {
                try {
                    if (response.statusCode == 200) {
                        resolve(body);
                    } else {
                        reject(error)
                    }
                } catch (error) {
                    reject(error)
                }
            })
        })
    },
    requestPOSTs(url, body) {
        return new Promise((resolve, reject) => {
            request({
                url: url,
                method: "POST",
                body: body
            }, function (error, response, body) {
                try {
                    if (response.statusCode == 200) {
                        resolve(body);
                    } else {
                        reject(error)
                    }
                } catch (error) {
                    reject(error)
                }
            })
        })
    },
    //发送请求
    requestGET(url) {
        return new Promise((resolve, reject) => {
            request({
                url: url,
                method: "GET",
                json: true,
                headers: {
                    "content-type": "application/json",
                },
            }, function (error, response, body) {
                try {
                    if (response.statusCode == 200) {
                        resolve(body);
                    } else {
                        reject(error)
                    }
                } catch (error) {
                    reject(error)
                }
            })
        })
    }
};
